package fr.axones.pocketagile.ui.view.main.account
{
	import fr.axones.pocketagile.vo.UserVO;
	
	import mx.validators.EmailValidator;
	import mx.validators.ValidationResult;
	
	import spark.components.TextInput;

	public class AccountManagementViewHelper
	{
		public function AccountManagementViewHelper()
		{
		}
		
		public static function validEmail(ti_email:TextInput):Boolean
		{
			if(ti_email.text.length == 0)
			{
				return false;
			}
			
			var a:Array = new EmailValidator().validate(ti_email.text).results;
			
			if(a == null || a.length == 0)
			{
				return true;
			}
			
			return (a[0] as ValidationResult).isError;
		}	
		
		public static function validForm(ti_email:TextInput, ti_password:TextInput, ti_password2:TextInput, ti_displayname:TextInput):String
		{
			var error:String = "";
			
			if(!validEmail(ti_email))
			{
				error += "email is not valid";
			}
			
			if(ti_password.text.length < 6 || ti_password2.text.length < 6) 
			{
				if(error.length != 0){
					error += ", ";
				}
				error += "password is not valid (need 6 characteres at least)";
			}
			
			if(ti_password2.text.length < 6) 
			{
				if(error.length != 0){
					error += ", ";
				}
				error += "retyped password is not valid (need 6 characteres at least)";
			}	
			
			if(ti_password.text != ti_password2.text){
				if(error.length != 0){
					error += ", ";
				}
				error += "passwords are not identical";
			}
			
			if(ti_displayname.text.length < 2) 
			{
				if(error.length != 0){
					error += ", ";
				}
				error += "display name is not valid (need 6 characteres at least)";
			}	
			
			return error;
		}
		
		public static function buildUpdateEvent(user:UserVO):AccountEvent
		{
			var e:AccountEvent = new AccountEvent(AccountEvent.UPDATE_USER);
			
			e.user = user;
			
			return e;
		}
	}
}